package com.dd.duu.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dd.dc.base.domain.DPage;
import com.dd.dc.base.domain.DResult;
import com.dd.dc.entity.users.DRole;
import com.dd.dc.entity.users.DUser;
import com.dd.dc.entity.users.DUserRoleRelation;
import com.dd.duu.service.RoleClient;
import com.dd.duu.service.UserClient;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 描述: 用户客户端Controller
 *
 * @author: yanglin
 * @Date: 2021-03-04-14:25
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/user/c/")
@GlobalTransactional(rollbackFor = Exception.class) // 分布式事务seata
public class UserController {

    @Autowired
    UserClient userClient;

    @Autowired
    RoleClient roleClient;

    @ApiOperation(value = "用户分页")
    @PostMapping("/queryUserList")
    public DResult<DPage<DUser>> queryUserList(@RequestParam int page, @RequestParam int limit, @RequestParam String queryByLoginName){
        log.info("UserUi queryUserList start ...");
        Page<DUser> pages = userClient.queryUserList(page, limit);
        DPage<DUser> userPage = DPage.to(pages);
        return DResult.of(userPage);
    }

    @Transactional
    @ApiOperation(value = "用户新增/更新")
    @PostMapping("saveOrUpdate")
    public DResult saveOrUpdate(@RequestBody DUser user){
        boolean flag = true;
        if (Objects.isNull(user.getUserId())) {
            // 用户新增
            userClient.insert(user);
        }else{
            // 用户更新
            userClient.updateById(user);
            // 更新用户角色关系
            // 删除
            roleClient.deleteUR(user.getUserId());
        }
        List<DRole> roles = user.getRoles();
        List<DUserRoleRelation> roleRelations = new ArrayList<>();
        if (roles.size() > 0){
            roles.forEach(r -> {
                DUserRoleRelation roleRelation =  new DUserRoleRelation().setUserId(user.getUserId()).setRoleId(r.getRoleId());
                roleRelations.add(roleRelation);
            });
            flag = roleClient.saveBatchUR(roleRelations);
        }
        return DResult.of(flag);
    }

    @Transactional
    @ApiOperation(value = "用户删除")
    @DeleteMapping("deleteUser")
    public DResult deleteUser(@RequestParam Integer userId){
        boolean flag = true;
        flag = userClient.delete(userId);
        if(flag){
            flag = roleClient.deleteUR(userId);
        }
        return DResult.of(flag);
    }
}
